//
//  LoadingPageViewController.m
//  CreditHub
//
//  Created by xinhualong on 2024/9/12.
//

#import "LoadingPageViewController.h"
#import "AppDelegate.h"
#import "XhlGuideViewController.h"
#import "TabbarViewController.h"
#import <CoreTelephony/CTCellularData.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>

@interface LoadingPageViewController ()
@property (nonatomic, strong) NSArray *arrayName;
@property (nonatomic, assign) NSInteger selectIndex;
@end

@implementation LoadingPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectIndex = 0;
    xhl_hudLoading();
//    [self requestStart];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"hasLaunchedBefore"]){
        [self testHttp];
    }
    [self checkCellularDataAuthorization];
}
-(void)testHttp {
    NSURL *url = [NSURL URLWithString:@"http://147.139.174.212:8575/like/should/glickdecember"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
    [dataTask resume];
}
- (IBAction)clickReload:(id)sender {
  
    
    [self checkCellularDataAuthorization];
}
- (void)checkCellularDataAuthorization {
    CTCellularData *cellularData = [[CTCellularData alloc] init];

        __weak typeof(self) weakSelf = self;
        cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state) {
            double delayInSeconds = 0.0;
            if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]){
                delayInSeconds = 1.0;
            }
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [weakSelf chuxin:state];
            });
            
        };

    
}

- (void)chuxin:(CTCellularDataRestrictedState)state{
  
    
    __weak typeof(self) weakSelf = self;
    switch (state) {
        case kCTCellularDataRestricted:
        case kCTCellularDataRestrictedStateUnknown:
        
            if(![weakSelf isFirstRequest]||weakSelf.buttonReload.hidden == NO){
                
                [weakSelf showAlertForNetworkPermission];
            }
            xhl_hudDismiss();
            weakSelf.buttonReload.hidden = NO;
            break;
        case kCTCellularDataNotRestricted:
        {
            
                xhl_hudLoading();
                [weakSelf requestStart];
           
            
        }
            
            break;
            
            
        default:
         
            break;
    }
   
    
}

- (BOOL)isFirstLaunch {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL hasLaunchedBefore = [defaults boolForKey:@"hasLaunchedBefore"];
    if (!hasLaunchedBefore) {
       
        return YES;
    }
    return NO;
}
- (BOOL)isFirstRequest {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL hasLaunchedBefore = [defaults boolForKey:@"hasLaunchedRequest"];
    if (!hasLaunchedBefore) {
//        [defaults setBool:YES forKey:@"hasLaunchedRequest"];
//        [defaults synchronize];
        return YES;
    }
    return NO;
}


- (void)cutName{
    
    if(self.arrayName.count > 0){
        if(self.arrayName.count > self.selectIndex){
            NSDictionary *dic = self.arrayName[self.selectIndex];
            if( [[BaseService sharedInstance].requestBaseUrl isEqualToString:CHString(dic[@"chi"])]  ){
                self.selectIndex +=1;
                [self cutName];
            }else{
                
//                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//                [defaults setObject:CHString(dic[@"chi"]) forKey:@"netUrlAddress"];
//                [defaults synchronize];
                [BaseService sharedInstance].requestBaseUrl = CHString(dic[@"chi"]);
                
                [self requestStart];
                self.selectIndex +=1;
            }
        }
    }else{
        NSError *error = nil;
        NSString  *arrayString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://in2-dc.oss-ap-southeast-1.aliyuncs.com/credit-hub/credit.json"] encoding:NSUTF8StringEncoding error:&error];
        if (error) {
            NSLog(@"Error converting string to array: %@", error);
//            xhl_showMessage(@"Request failed");
            xhl_hudDismiss();
            self.selectIndex = 0;
            self.buttonReload.hidden = NO;
            return;
        }
        // 转换字符串为 NSData
        NSData *data = [arrayString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error1 = nil;
        
        // 解析 JSON 数据为 NSArray
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1];
        
        if (error1) {
            NSLog(@"Error converting string to array: %@", error);
//            xhl_showMessage(@"Request failed");
            xhl_hudDismiss();
            self.selectIndex = 0;
            self.buttonReload.hidden = NO;
        } else {
            NSLog(@"Array: %@", array);
            self.arrayName = array;
            if(self.arrayName.count > self.selectIndex){
                NSDictionary *dic = self.arrayName[self.selectIndex];
                if( [[BaseService sharedInstance].requestBaseUrl isEqualToString:CHString(dic[@"chi"])]  ){
                    self.selectIndex +=1;
                    [self cutName];
                }else{
                    [BaseService sharedInstance].requestBaseUrl = CHString(dic[@"chi"]);
//                    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//                    [defaults setObject:CHString(dic[@"chi"]) forKey:@"netUrlAddress"];
//                    [defaults synchronize];
                    [self requestStart];
                    self.selectIndex +=1;
                }
            }else{
//                xhl_showMessage(@"Request failed");
                xhl_hudDismiss();
                self.selectIndex = 0;
                self.arrayName = [NSArray array];
            }
        }
        NSLog(@"------------%@",array);
    }
}

- (void)requestStart{
    
    NSLog(@"------------请求了数据");
    NSString *systemLanguage = [[NSLocale preferredLanguages] firstObject];
    
    __weak typeof(self) weakSelf = self;
    [BaseService requestForHttpGet:@"/proud/soundly" parameters:@{@"soundly":systemLanguage,@"slept":@([JKMVKeyChainUUID dailiZhuangTaiStatus]),@"hadn":@([JKMVKeyChainUUID shiFouKaiQiVPN])} success:^(NSURLSessionDataTask *task, id response) {
        if([response[@"ofexcitement"] integerValue] == 0){
            xhl_hudDismiss();
            [weakSelf fdinfo:response[@"pity"][@"flung"]];
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSMutableDictionary *dicAuth = [NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:@"LocationAlertAuth"]];
            [defaults setBool:YES forKey:@"hasLaunchedRequest"];
            NSDate *currentDate = [NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSString *formattedDate = [dateFormatter stringFromDate:currentDate];
            
            NSString *bottom = CHString(response[@"pity"][@"bottom"]);
            if([bottom isEqualToString:@"1"]){
                
                if (dicAuth.count > 0) {
                    NSString *date = [dicAuth objectForKey:@"date"];
                    if([date isEqualToString:formattedDate]){
                        [dicAuth setObject:@"2" forKey:@"show"];
                    }else{
                        [dicAuth setObject:@"1" forKey:@"show"];
                    }
                }else{
                    [dicAuth setObject:@"1" forKey:@"show"];
                }
                
            }else{
                [dicAuth setObject:bottom forKey:@"show"];
            }
            
            [defaults setObject:dicAuth forKey:@"LocationAlertAuth"];
            [defaults synchronize];
           
            [weakSelf rootViewController];
        }else{
//            weakSelf.buttonReload.hidden = NO;
//            xhl_showMessage(response[@"shared"]);
//            [weakSelf checkNetworkStatus];
            [weakSelf cutName];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        weakSelf.buttonReload.hidden = NO;
//        xhl_hudDismiss();
//        [weakSelf checkCellularDataAuthorization];
        [weakSelf cutName];
        
      
      
    }];
}

- (void)rootViewController{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if([self isFirstLaunch]){
       
        appDelegate.window.rootViewController = [[XhlGuideViewController alloc] init];
    }else{
        
        TabbarViewController *tabbarVC = [[TabbarViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:tabbarVC];
        appDelegate.window.rootViewController = nav;
    }
   
    [appDelegate.window makeKeyAndVisible];
}

- (void)fdinfo:(NSDictionary *)dicInfo{
    
    if(dicInfo.count== 0){
        return;
    }
 
    [FBSDKSettings sharedSettings].appID = CHString(dicInfo[@"comforted"]);
    [FBSDKSettings sharedSettings].displayName = CHString(dicInfo[@"jabbered"]);
    [FBSDKSettings sharedSettings].clientToken = CHString(dicInfo[@"mean"]);
    [FBSDKSettings sharedSettings].appURLSchemeSuffix = CHString(dicInfo[@"heundressed"]);
    [FBSDKSettings sharedSettings].isAutoLogAppEventsEnabled = YES;
    [[FBSDKApplicationDelegate sharedInstance] application:self.application didFinishLaunchingWithOptions:self.launchOptions];

}
// 显示网络权限提示的 Alert
- (void)showAlertForNetworkPermission {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Network unavailable"
                                                                                 message:@"Please check your network permission Settings or network connection to ensure that the application is working properly."
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"Go to Settings"
                                                                 style:UIAlertActionStyleDefault
                                                               handler:^(UIAlertAction * _Nonnull action) {
            // 打开设置
            NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
                [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:settingsAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
